<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas 时间轴</title>
  <style>
    body {
      text-align: center;
      margin-top: 20px;
    }
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <h2>时间轴示例</h2>
  <canvas id="timeline" width="800" height="300"></canvas>

  <script>
    // 时间轴数据配置
    const timelineData = [
      { name: "胡日鹏", date: "2021.01" },
      { name: "吴琼", date: "2023.04" },
      { name: "伍衡", date: "2023.04" },
      { name: "马超", date: "2023.09" },
      { name: "黄振洲", date: "2023.09" },
      { name: "赵湘文", date: "2023.09" },
      { name: "何昆", date: "2023.12" }
    ];

    const canvas = document.getElementById("timeline");
    const ctx = canvas.getContext("2d");

    // 时间轴配置
    const START_X = 50; // 起始x坐标
    const END_X = 750;  // 结束x坐标
    const BASE_Y = 150; // 基准y坐标
    const LINE_WIDTH = 3; // 轴线宽度
    const POINT_RADIUS = 5; // 标记点大小
    const FONT = "12px Arial"; // 字体大小和类型

    // 计算时间点的 x 坐标
    function getXPosition(date, minDate, maxDate) {
      const totalRange = maxDate - minDate;
      const currentRange = date - minDate;
      return START_X + (currentRange / totalRange) * (END_X - START_X);
    }

    // 日期转换函数（字符串转为日期对象的时间戳）
    function parseDate(dateStr) {
      const [year, month] = dateStr.split(".").map(Number);
      return new Date(year, month - 1).getTime();
    }

    // 渲染时间轴
    function renderTimeline(data) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      // 提取时间的最小和最大值
      const dates = data.map(item => parseDate(item.date));
      const minDate = Math.min(...dates);
      const maxDate = Math.max(...dates);

      // 绘制横线
      ctx.beginPath();
      ctx.moveTo(START_X, BASE_Y);
      ctx.lineTo(END_X, BASE_Y);
      ctx.lineWidth = LINE_WIDTH;
      ctx.strokeStyle = "#2a6fb2";
      ctx.stroke();

      // 绘制时间点和标记
      data.forEach(item => {
        const x = getXPosition(parseDate(item.date), minDate, maxDate);

        // 绘制垂直线
        ctx.beginPath();
        ctx.moveTo(x, BASE_Y);
        ctx.lineTo(x, BASE_Y - 50);
        ctx.lineWidth = 1;
        ctx.strokeStyle = "#2a6fb2";
        ctx.stroke();

        // 绘制标记点
        ctx.beginPath();
        ctx.arc(x, BASE_Y, POINT_RADIUS, 0, 2 * Math.PI);
        ctx.fillStyle = "#2a6fb2";
        ctx.fill();

        // 显示姓名
        ctx.font = FONT;
        ctx.fillStyle = "#000";
        ctx.textAlign = "center";
        ctx.fillText(item.name, x, BASE_Y - 60);

        // 显示时间
        ctx.fillStyle = "#666";
        ctx.fillText(item.date, x, BASE_Y + 20);
      });

      // 绘制箭头
      ctx.beginPath();
      ctx.moveTo(END_X, BASE_Y);
      ctx.lineTo(END_X - 10, BASE_Y - 5);
      ctx.lineTo(END_X - 10, BASE_Y + 5);
      ctx.closePath();
      ctx.fillStyle = "#2a6fb2";
      ctx.fill();
    }

    renderTimeline(timelineData); // 执行渲染
  </script>
</body>
</html>
